#include "mystdio.h"


static MYFILE* BuyFile(int fd, int flag){
	MYFILE* fc = malloc(sizeof(MYFILE));
	if(!fc){
		perror("malloc fail");
		return NULL;
	}
	fc->fileno = fd;
	fc->flag = flag;
	fc->bufferlen = 0;
	fc->flush_method = LINE_FLUSH;
	memset(fc->outbuffer, 0, sizeof(fc->outbuffer));
	
	return fc;
}

MYFILE* MYFopen(const char* path, const char* mode)
{
	int fd = -1;
	int flag = 0;
	if(strcmp(mode, "w") == 0){
		flag = O_CREAT | O_WRONLY | O_TRUNC;
		fd = open(path, flag, 0666);
	}
	else if(strcmp(mode, "a") == 0){
		flag = O_CREAT | O_WRONLY | O_APPEND;
		fd = open(path, flag, 0666);
	}
	else if(strcmp(mode, "r") == 0){
		flag = O_RDONLY;
		fd = open(path, flag);
	}
	else{
		perror("mode fail");
		return NULL;
	}
	
	if(fd < 0)
		return NULL;
		
	return BuyFile(fd, flag);
}

void MYFFlush(MYFILE* file)
{
	int n = write(file->fileno, file->outbuffer, file->bufferlen);
	(void) n;
	fsync(file->fileno);
	file->bufferlen = 0;
}

void MYFclose(MYFILE* file)
{
	if(file->fileno < 0)
		return;
		
	MYFFlush(file);
	close(file->fileno);
	free(file);
}

int MYFwrite(MYFILE* file, void* str, int len)
{
	// 1、直接拷贝
	const char* dwrite = (const char*) str;
	memcpy(file->outbuffer, dwrite, sizeof(char) * len);
	file->bufferlen = len;
	
	//2、判断是否要刷新
	if(file->flush_method == LINE_FLUSH && file->outbuffer[file->bufferlen-1] == '\n')
		MYFFlush(file);
		
	return 0;
}


